% created by tyy on 2023/11/06
function [x_out,f_out,cnt,time,code] = f_bisection_method(equation,range,tolerance,maxIteration)
% 二分法
syms x; % Declare symbolic variable

% Define the interval [a, b] where the root is expected
a = range(1);
b = range(2);

tic;
% Bisection method implementation
for i = 1:maxIteration
    c = (a + b) / 2;
    % new_r = double(subs(equation, x, c));
    new_r = subs(equation, x, c);
    if abs(double(new_r)) <= tolerance
        code = 0;
        break;
    elseif (b - a) / 2 < tolerance*1e-2
        code = 1;
        break;
    end
    if sign(new_r) == sign(subs(equation, x, a)) % 两者的结果都大于0或小于0，调整左侧范围
        a = c;
    else
        b = c;
    end
end
% toc;
time = toc;
if (i >= maxIteration) 
    code = -1; 
end
x_out = c;
f_out = subs(equation,x,x_out);
cnt = i;

